package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"news/models"
	"strconv"
)

type NewController struct {
	beego.Controller
}

func (c *NewController) Add() {
	title := c.GetString("title")
	createAt := c.GetString("create_at")
	types := c.GetString("types")
	var news = models.New{

		Title:    title,
		CreateAt: createAt,
		Types:    types,
	}
	err := models.DB.Create(&news).Error
	if err != nil {
		c.Data["json"] = models.JsonR{
			Code: 500,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = models.JsonR{
		Code: 200,
		Msg:  "添加成功",
		Data: nil,
	}
	c.ServeJSON()
}

func (c *NewController) List() {

	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 3)
	var count int64
	models.DB.Model(&models.New{}).Count(&count)
	var news []models.New
	pageDate := make(map[string]interface{})
	key := "new" + strconv.Itoa(page)
	val, err := models.Rds.Get(key).Result()
	if err != nil {

		err = models.DB.Find(&news).Error
		if err != nil {
			c.Data["json"] = models.JsonR{
				Code: 500,
				Msg:  "展示失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		}

		pageDate["page"] = page
		pageDate["count"] = count
		pageDate["size"] = size
		pageDate["news"] = news
		value, _ := json.Marshal(&pageDate)
		models.Rds.Set(key, value, 0)
		c.Data["json"] = models.JsonR{
			Code: 200,
			Msg:  "展示成功-mysql",
			Data: pageDate,
		}
		c.ServeJSON()
	} else {
		json.Unmarshal([]byte(val), &pageDate)
		c.Data["json"] = models.JsonR{
			Code: 200,
			Msg:  "展示成功-redis",
			Data: pageDate,
		}
		c.ServeJSON()
	}

}
func (c *NewController) Update() {
	id, _ := c.GetInt("id")
	title := c.GetString("title")
	createAt := c.GetString("create_at")
	types := c.GetString("types")
	var news = models.New{
		Id:       id,
		Title:    title,
		CreateAt: createAt,
		Types:    types,
	}
	err := models.DB.Updates(&news).Error
	if err != nil {
		c.Data["json"] = models.JsonR{
			Code: 500,
			Msg:  "修改失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = models.JsonR{
		Code: 200,
		Msg:  "修改成功",
		Data: nil,
	}
	c.ServeJSON()
}

func (c *NewController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Delete(&models.New{}, id).Error
	if err != nil {
		c.Data["json"] = models.JsonR{
			Code: 500,
			Msg:  "删除失败-mysql",
			Data: nil,
		}
		c.ServeJSON()
		return
	}

	key := "new" + strconv.Itoa(id)
	err = models.Rds.Del(key).Err()
	if err != nil {
		c.Data["json"] = models.JsonR{
			Code: 500,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = models.JsonR{
		Code: 200,
		Msg:  "删除成功-redis",
		Data: nil,
	}
	c.ServeJSON()

}
